<?php

namespace app\service;

use alipay\AlipayTradeOrderSettleQueryRequest;
use alipay\AlipayTradeOrderSettleRequest;
use alipay\AlipayTradeRoyaltyRelationBatchqueryRequest;
use alipay\AlipayTradeRoyaltyRelationBindRequest;
use alipay\AlipayTradeSettleConfirmRequest;
use alipay\AntMerchantExpandIndirectImageUploadRequest;
use alipay\AntMerchantExpandIndirectZftorderQueryRequest;
use alipay\AopClient;

use alipay\AlipayOpenAuthTokenAppRequest;

//查询物业token


use alipay\AlipaySystemOauthTokenRequest;

//换取授权访问令牌
use alipay\AlipayTradeCreateRequest;

//生成订单
use alipay\AlipayTradeCloseRequest;
use stdClass;
use think\Db;
use think\facade\Log;

class zftService
{
    const PRIKEYPATH = '/www/wwwroot/zaozao/public/rsa/zft/prikey.txt';//私钥路径
    const PUBKEYPATH = '/www/wwwroot/zaozao/public/rsa/zft/alipay_pubkey.txt';//支付宝公钥路径


    private $app_id;//支付宝分配给开发者的应用
    private $method;//接口名称
    private $format;//仅支持JSON  no
    private $charset = 'UTF-8';//请求使用的编码格式，如utf-8,gbk,gb2312等
    private $sign_type = 'RSA2';//商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
    private $sign;//商户请求参数的签名串  no
    private $timestamp;//发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"
    private $version = '1.0';//调用的接口版本，固定为：1.0
    private $app_auth_token;//详见应用授权概述 no
    private $biz_content;//请求参数的集合，最大长度不限，除公共参数外所有请求参数都必须放在这个参数中传递，具体参照各产品快速接入文档

    private $apiUrl; // no



    //XIOA
    public function xcxgetPublicContent()
    {
        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2021001164679293';//2019061665593126
        $aop->rsaPrivateKey = file_get_contents(self::PRIKEYPATH);//私钥路径
        $aop->alipayrsaPublicKey = file_get_contents(self::PUBKEYPATH);//支付宝公钥路径
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        return $aop;
    }
    //换取授权访问令牌
    public function oauthToken($code){
        $aop = $this->xcxgetPublicContent();
        $request = new AlipaySystemOauthTokenRequest ();
        $request->setGrantType("authorization_code");
        $request->setCode($code);
        $request->setRefreshToken('');
        $result = $aop->execute ( $request);
        if(property_exists($result,'error_response')){
            $responseNode = 'error_response';
        }else{
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        }
        return $result->$responseNode;
    }


    //小程序换取授权访问令牌
    public function xcxoauthToken($code)
    {
        $aop = $this->xcxgetPublicContent();
        $request = new AlipaySystemOauthTokenRequest ();
        $request->setGrantType("authorization_code");
        $request->setCode($code);
        $request->setRefreshToken('');
        $result = $aop->execute($request);
        if (property_exists($result, 'error_response')) {
            $responseNode = 'error_response';
        } else {
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        }
        return $result->$responseNode;
    }

    //分账关系绑定
    public function royaltyRelationBind($data)
    {
        $data = json_decode($data);
        $aop = $this->xcxgetPublicContent();
        $request = new AlipayTradeRoyaltyRelationBindRequest ();
        $request->setBizContent("{" .
            "  \"receiver_list\":[" .
            "    {" .
            "      \"type\":\"$data->type\"," .
            "      \"account\":\"$data->account\"," .
            "      \"name\":\"$data->name\"," .
            "      \"memo\":\"$data->memo\"" .
            "    }" .
            "  ]," .
            "  \"out_request_no\":\"$data->out_request_no\"" .
            "}");
//        $token = $data->token;
//        $result = $aop->execute($request, null, $token);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }


    //分账关系解绑
    public function royaltyRelationUnbind($data)
    {

    }

    //分账关系查询
    public function royaltyRelationBatchquery($data)
    {
        $data = json_decode($data);
        $aop = $this->xcxgetPublicContent();
        $request = new AlipayTradeRoyaltyRelationBatchqueryRequest ();
        $model = array();
        // 设置几页
        $model['page_num'] = 1;

        // 设置页面大小
        $model['page_size'] = 20;


        $model['out_request_no'] =$data->out_request_no;

        $request->setBizContent(json_encode($model,JSON_UNESCAPED_UNICODE));
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    //生成订单
    public function create($data)
    {
        $data = json_decode($data);

        $aop = $this->xcxgetPublicContent();
        $request = new AlipayTradeCreateRequest ();
        $object = new stdClass();

        /*$request->setBizContent("{" .
            "\"out_trade_no\":\"$data->out_trade_no\"," .
            "\"total_amount\":$data->total_amount," .
            "\"subject\":\"$data->subject\"," .
            "\"buyer_id\":\"$data->buyer_id\"," .
            "\"sell_id\":\"$data->sell_id\"," .
            "\"extend_params\":{".
            "\"sys_service_provider_id\":\"2088131393104892\"".
            "},".
            "\"timeout_express\":\"100m\"" .
            "  }");*/
        $object->out_trade_no = $data->out_trade_no;
        $object->total_amount = $data->total_amount;
        $object->subject = $data->subject;
        $object->buyer_id = $data->buyer_id;
        //$object->sell_id=$data->sell_id;

        $extendParams = [
            'sys_service_provider_id' => '2088131393104892',
        ];
        $object->extend_params = $extendParams;

        $settleInfo = [
            'settle_detail_infos' => [
                [
                    'trans_in_type' => $data->settle_detail_info->trans_in_type,
                    'trans_in' => $data->settle_detail_info->trans_in,
                    'amount' => $data->settle_detail_info->amount,
                ]
            ]
        ];
        $object->settle_info = $settleInfo;

        //二级商户编号
        $subMerchant = [
            'merchant_id' => $data->merchant_id,
        ];
        $object->sub_merchant = $subMerchant;
        $object->product_code = 'JSAPI_PAY';//   JSAPI_PAY FACE_TO_FACE_PAYMENT
        $json = json_encode($object);

        //Log::write($json);
        $request->setBizContent($json);
        $request->setNotifyUrl($data->notifyUrl);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    //银行卡收款
    public function create2($data)
    {
        $data = json_decode($data);

        $aop = $this->xcxgetPublicContent();
        $request = new AlipayTradeCreateRequest ();
        $object = new stdClass();


        $object->out_trade_no = $data->out_trade_no;
        $object->total_amount = $data->total_amount;
        $object->subject = $data->subject;
        $object->buyer_id = $data->buyer_id;
        //$object->sell_id=$data->sell_id;

        $extendParams = [
            'sys_service_provider_id' => '2088131393104892',
        ];
        $object->extend_params = $extendParams;

        $settleInfo = [
            'settle_detail_infos' => [
                [
                    'trans_in_type' => $data->settle_detail_info->trans_in_type,
                    'trans_in' => $data->settle_detail_info->trans_in,
                    'amount' => $data->settle_detail_info->amount,
                ]
            ]
        ];
        $object->settle_info = $settleInfo;

        //二级商户编号
        $subMerchant = [
            'merchant_id' => '2088610162385563',
        ];
        $object->sub_merchant = $subMerchant;
        $object->product_code = 'FACE_TO_FACE_PAYMENT';
        $json = json_encode($object);

        Log::write($json);
        $request->setBizContent($json);
        $request->setNotifyUrl($data->notifyUrl);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    //返佣结算
    public function settle($data)
    {
        $data = json_decode($data);
        $aop = $this->xcxgetPublicContent();
        $request = new AlipayTradeOrderSettleRequest ();
        $object = new stdClass();


        $object->out_request_no = $data->out_trade_no;
        $object->trade_no = $data->trade_no;
        $royalty_parameters = [
            [
                'royalty_type' => $data->royalty_parameters->royalty_type,//分账类型
                'trans_in_type' => $data->royalty_parameters->trans_in_type,//收入方账户类型
                'trans_in' => $data->royalty_parameters->trans_in,//收入方账户\
                'amount' => $data->royalty_parameters->amount,//分账金额
            ],
        ];
        $extend_params=[
            "royalty_finish"=>"true"
        ];

        $object->royalty_parameters = $royalty_parameters;
        $object->extend_params =$extend_params;
        $json = json_encode($object);
        Log::write($json);
        $request->setBizContent($json);
        /*$royalty_parameters=$data->royalty_parameters;
        $str="{" .
                "\"out_request_no\":\"$data->out_trade_no\"," .
                "\"trade_no\":\"$data->trade_no\"," .
                "\"royalty_parameters\":[" .
                    "{" .
                        "\"royalty_type\":\"$royalty_parameters->royalty_type\"," .
                        "\"trans_out\":\"$royalty_parameters->trans_out\"," .
                        "\"trans_out_type\":\"$royalty_parameters->trans_out_type\"," .
                        "\"trans_in_type\":\"$royalty_parameters->trans_in_type\"," .
                        "\"trans_in\":\"$royalty_parameters->trans_in\"," .
                        "\"amount\":$royalty_parameters->amount" .
                    "}" .
                "]" .
            "}";
        Log::write($str);
        $request->setBizContent($str);*/
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    public function settleQuery($data)
    {
        $data = json_decode($data);
        $aop = $this->xcxgetPublicContent();
        $request = new AlipayTradeOrderSettleQueryRequest ();
        $object = new stdClass();
        $object->settle_no = $data->settle_no;
        $json = json_encode($object);

        $request->setBizContent($json);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }
    public function settleQuery2($data)
    {
        $data = json_decode($data);
        $aop = $this->xcxgetPublicContent();
        $request = new AlipayTradeOrderSettleQueryRequest ();
        $object = new stdClass();
        $object->trade_no = $data->trade_no;
        $object->out_request_no = $data->out_request_no;
        $json = json_encode($object);

        $request->setBizContent($json);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    public function zftorderQuery($data)
    {
        $data = json_decode($data);
        $aop = $this->xcxgetPublicContent();
        $request = new AntMerchantExpandIndirectZftorderQueryRequest ();
        $request->setBizContent("{" .
            "\"external_id\":\"$data->external_id\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }

    public function settleComfirm($data){
        $data = json_decode($data);
        $aop = $this->xcxgetPublicContent();
        $request = new AlipayTradeSettleConfirmRequest();

        $model = array();

        // 设置确认结算请求流水号
        $model['out_request_no'] = $data->out_trade_no;

        // 设置支付宝交易号
        $model['trade_no'] = $data->trade_no;;

        // 设置描述结算信息
        $settleInfo = array();
        $settleDetailInfos = array();
        $settleDetailInfos0 = array();
        $settleDetailInfos0['royalty_type'] = $data->royalty_parameters->royalty_type;//分账类型
        $settleDetailInfos0['amount'] = $data->royalty_parameters->amount;
        $settleDetailInfos0['trans_in'] =$data->royalty_parameters->trans_in;

        $settleDetailInfos0['trans_in_type'] =$data->royalty_parameters->trans_in_type;
        $settleDetailInfos[] = $settleDetailInfos0;
        $settleInfo['settle_detail_infos'] = $settleDetailInfos;
        $model['settle_info'] = $settleInfo;

        // 设置扩展字段信息
        $extendParams = array();
        $extendParams['royalty_freeze'] = "true";
        $model['extend_params'] = $extendParams;


        $request->setBizContent(json_encode($model,JSON_UNESCAPED_UNICODE));
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }
    public function imageUpload($data){
        $data = json_decode($data);
        $aop = $this->xcxgetPublicContent();
        $request = new  AntMerchantExpandIndirectImageUploadRequest();
        $request->setImageType($data->imageType);
        $request->setImageContent("@".$data->imageUrl);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        return $result->$responseNode;
    }
}